package com.miraclebenelux.ean;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Site {
  public String expr;
  public String url;
  public String name;
  public String search;
  public String search_page;
  public String pgid;
  public String sid;
  public String jses;
  public String seq;
  public boolean enabled;
  
  public Site(String p_expr, String p_url, String p_name, String p_search)
  {
	  expr = p_expr;
	  url  = p_url;
	  name = p_name;
	  search = p_search;
      enabled = true;
      
	  search_page = fetchURL(p_search);	  
	  pgid   = getStr("pgid=");
	  sid    = getStr("fh_session=");
	  //jses   = getStr("jses=");
	  //seq    = getStr("seq=");
  }
  
  public void Enable()
  {
	  enabled = true;
  }
  
  public void Disable()
  {
	  enabled = false;
  }
  
  private String fetchURL(String p_url)
  {
        try {
        	int len;
        	String result = null;
            URL url = new URL(p_url);
            URLConnection connection = url.openConnection();
            
            //BufferedReader in = new BufferedReader(
            //        new InputStreamReader(connection.getInputStream())
            //);
            
            InputStreamReader in =
                 new InputStreamReader(connection.getInputStream());
          
            //String tot="";
            char  tot[] = new char[50000];
            
            len = in.read(tot);
            in.close();
            result = new String(tot);
            return result;
        } catch (MalformedURLException e) {
            // ...
        	return null;
        } catch (IOException e) {
            // ...
        	return null;
        }	
	}
  
  private String getStr(String param)
  {
	  int pos ;

	  int begin_pos;
	  int len = param.length();
	  boolean ready = false;
	  
	  if (search_page == null)
	  {
		  return null;
	  }
	  
	  pos = search_page.indexOf(param);
	  
	  if (pos < 0)
	  {
		  return null;
	  }
	  else
	  {
		  begin_pos = pos + len;
		  for (int i=begin_pos; !ready; i++)
		  {
			  if (search_page.charAt(i) == ';' || search_page.charAt(i) == '?' || search_page.charAt(i) == '"')
			  {
				  if ((i-1) < 0)
				  {
					  return null;
				  }
				  return search_page.substring(begin_pos, (i-1));
			  }
			  else
			  {
				 if (i >= search_page.length())
				 {
					 return null;
				 }
			  }
		  }		  
	  }
	  return null;
  }
  
}
